package mySeleniumDriver;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailingTestResults extends BaseClass {

  public void sendmailAttachment(String zipfilepath) {
    try {

      final String mailAuthentication[] = gs_emailAuth.split(":");
      String smptDetails[] = gs_emailSMTP.split(":");

      String fileAttachment = zipfilepath;
      String fileAttachmentFullPath[] = fileAttachment.split("\\\\");
      String fileAttachmentName = fileAttachmentFullPath[fileAttachmentFullPath.length - 1];

      // Get system properties
      // Properties props = System.getProperties();
      Properties props = new Properties();
      // Setup mail server
      props.put("mail.smtp.host", smptDetails[0]);
      props.put("mail.smtp.socketFactory.port", smptDetails[1]);
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", smptDetails[1]);
      // Get session
      Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(mailAuthentication[0], mailAuthentication[1]);
        }
      });
      // try {
      // Define message
      Message message = new MimeMessage(session);

      message.setFrom(new InternetAddress(gs_emailFROM));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(gs_emailTO));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(gs_emailCC));
      message.setSubject(gs_emailSubject + ":[Passed=" + Math.round(totalScriptsPassed)
          + "; Failed=" + Math.round(totalScriptsFailed) + "]");
      message.setText("Body of the email");



      // create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();

      // fill message
      // messageBodyPart.setText("Dear User, \n\nPlease find the Automation Test Summary Report attached. \n\n ****THIS IS AN AUTO GENERATED EMAIL.****");
      messageBodyPart.setContent(getEmailBody(), "text/html");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      // Part two is attachment
      messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(fileAttachment);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(fileAttachmentName);
      multipart.addBodyPart(messageBodyPart);

      // Put parts in message
      message.setContent(multipart);

      // Send the message
      Transport.send(message);
      log("info", "Email sent successfully!");
    } catch (Exception e) {
      log("error", "Exception in Sending E-Mail:" + e.getMessage());

    }

  }

  public String getEmailBody() {

    String testSetToPrint[] = TestSuite.split("\\\\");

    String emailBody = "";
    emailBody =
        "<b>Dear User,</b><br>"
            + "Please find the Automation Test Summary Report attached.<br><br>"
            + "<table border=1><tr ><td colspan=2 bgcolor=yellow> <b><center>Test Result Summary</center></b></td></tr>"
            + "<tr><td bgcolor=lightblue>Test Set Name</td><td>"
            + testSetToPrint[testSetToPrint.length - 1].replace("xls", "")
            + "</td></tr>"
            + "<tr><td bgcolor=lightblue>Environment</td><td>"
            + gs_testEnvironment
            + "</td></tr>"
            + "<tr><td bgcolor=lightblue>Total Execution Time</td><td>"
            + totalExecutionTime
            + "</td></tr>"
            + "<tr><td bgcolor=lightblue>Total No of Test cases</td><td>"
            + Math.round((totalScriptsPassed + totalScriptsFailed))
            + "</td></tr>"
            + "</table>"
            + "<br><table border=1><tr bgcolor=lightblue><td>Status</td><td>Count</td><td>Percentage</td></tr>"
            + "<tr><td bgcolor=green>Passed</td><td>"
            + Math.round(totalScriptsPassed)
            + "</td><td>"
            + Math.round((totalScriptsPassed / (totalScriptsPassed + totalScriptsFailed) * 100))
            + "%</td></tr>"
            + "<tr><td bgcolor=red>Failed</td><td>"
            + Math.round(totalScriptsFailed)
            + "</td><td>"
            + Math.round((totalScriptsFailed / (totalScriptsPassed + totalScriptsFailed) * 100))
            + "%</td></tr>"
            + "</table>"
            +

            "<br><br><table border=1><tr bgcolor=lightblue><td><b>Test Case Name</b></td><td><b>Status</b></td></tr>";

    for (String key : testResultsMap.keySet()) {
      if (testResultsMap.get(key).equalsIgnoreCase("passed"))
        emailBody =
            emailBody + "<tr><td><font color=green>" + key
                + "</font></td><td color=green><font color=green> " + testResultsMap.get(key)
                + "</font></td></tr> ";
      if (testResultsMap.get(key).equalsIgnoreCase("failed"))
        emailBody =
            emailBody + "<tr><td><font color=red>" + key + "</font></td><td><font color=red> "
                + testResultsMap.get(key) + "</font></td></tr> ";
    }

    emailBody = emailBody + "</table>" +

    "<br><br>****THIS IS AN AUTO GENERATED EMAIL.****";



    return emailBody;
  }

}
